﻿using System;
using System.Text;

/// <summary>
/// Base64Helper 的摘要说明  来源于网络
/// </summary>
public class Base64
{
    /// <summary>
    /// Base64编码，采用utf8编码方式编码
    /// </summary>
    /// <param name="source">待编码的明文</param>
    /// <returns>编码后的字符串</returns>
    public static string Base64Encode(string source)
    {
        return Base64Encode(Encoding.UTF8, source);
    }

    /// <summary>
    /// Base64编码
    /// </summary>
    /// <param name="encodeType">编码采用的编码方式</param>
    /// <param name="source">待编码的明文</param>
    /// <returns></returns>
    public static string Base64Encode(Encoding encodeType, string source)
    {
        string encode = string.Empty;
        byte[] bytes = encodeType.GetBytes(source);
        try
        {
            encode = Convert.ToBase64String(bytes);
        }
        catch
        {
            encode = source;
        }
        return encode;
    }

    /// <summary>
    /// Base64解码，采用utf8编码方式解码
    /// </summary>
    /// <param name="result">待解码的密文</param>
    /// <returns>解码后的字符串</returns>
    public static string Base64Decode(string result)
    {
        return Base64Decode(Encoding.UTF8, result);
    }

    /// <summary>
    /// Base64解码
    /// </summary>
    /// <param name="encodeType">解码采用的编码方式，注意和编码时采用的方式一致</param>
    /// <param name="result">待解码的密文</param>
    /// <returns>解码后的字符串</returns>
    public static string Base64Decode(Encoding encodeType, string result)
    {
        string decode = string.Empty;
        byte[] bytes = Convert.FromBase64String(result);
        try
        {
            decode = encodeType.GetString(bytes);
        }
        catch
        {
            decode = result;
        }
        return decode;
    }
}